const BASE_URL = 'http://121.37.1.66:8081';

export const api = {
  // 获取设备列表
  async getDevices(token) {
    try {
      const res = await uni.request({
        url: `${BASE_URL}/api/devices/`,
        method: 'GET',
        header: {
          'Authorization': token,
          'Content-Type': 'application/json'
        },
        timeout: 15000
      });
      
      // 统一响应处理
      const response = Array.isArray(res) ? res[1] : res;
      if (!response) {
        throw new Error('无效的响应格式');
      }
      
      if (response.statusCode !== 200) {
        throw new Error(`请求失败，状态码：${response.statusCode}`);
      }
      
      // 确保返回的数据是数组格式
      let data = response.data?.data || response.data;
      if (!Array.isArray(data)) {
        console.warn('API返回的数据不是数组格式，已转换为数组:', data);
        data = data ? [data] : []; // 如果不是数组，尝试转换为数组
      }
      
      return {
        code: response.data?.code || 1,
        msg: response.data?.msg || 'success',
        data: data
      };
    } catch (err) {
      console.error('获取设备列表失败:', err);
      throw new Error(err.message || '获取设备列表失败');
    }
  },

  // 绑定设备
  async bindDevice(device_id, token) {
    try {
      const userInfo = uni.getStorageSync('userInfo');
      if (!userInfo || !userInfo.userId) {
        throw new Error('用户信息不完整');
      }
      
      const res = await uni.request({
        url: `${BASE_URL}/api/devices/bind?slaveId=${device_id}&userId=${userInfo.userId}`,
        method: 'PUT',
        header: {
          'Authorization': token,
          'Content-Type': 'application/json'
        },
        timeout: 15000
      });
      
      const response = Array.isArray(res) ? res[1] : res;
      if (!response || response.statusCode !== 200) {
        throw new Error(response ? `请求失败，状态码：${response.statusCode}` : '无效的响应');
      }
      
      return {
        code: response.data?.code || 1,
        msg: response.data?.msg || 'success',
        data: response.data?.data || response.data
      };
    } catch (err) {
      console.error('绑定设备失败:', err);
      throw new Error(err.message || '绑定设备失败');
    }
  },

  // 添加设备
  async addDevice(deviceData, token) {
    try {
      const res = await uni.request({
        url: `${BASE_URL}/api/devices/`,
        method: 'POST',
        header: {
          'Authorization': token,
          'Content-Type': 'application/json'
        },
        data: {
          deviceName: deviceData.deviceName,
          location: deviceData.location,
          serialNumber: deviceData.serialNumber,
          status: deviceData.status || 0
        },
        timeout: 15000
      });
      
      const response = Array.isArray(res) ? res[1] : res;
      if (!response || response.statusCode !== 200) {
        throw new Error(response ? `请求失败，状态码：${response.statusCode}` : '无效的响应');
      }
      
      return {
        code: response.data?.code || 1,
        msg: response.data?.msg || 'success',
        data: response.data?.data || response.data
      };
    } catch (err) {
      console.error('添加设备失败:', err);
      throw new Error(err.message || '添加设备失败');
    }
  },

  // 更新设备信息
  async updateDevice(deviceData, token) {
    try {
      const res = await uni.request({
        url: `${BASE_URL}/api/devices/`,
        method: 'PUT',
        header: {
          'Authorization': token,
          'Content-Type': 'application/json'
        },
        data: deviceData,
        timeout: 15000
      });
      
      const response = Array.isArray(res) ? res[1] : res;
      if (!response || response.statusCode !== 200) {
        throw new Error(response ? `请求失败，状态码：${response.statusCode}` : '无效的响应');
      }
      
      return {
        code: response.data?.code || 1,
        msg: response.data?.msg || 'success',
        data: response.data?.data || response.data
      };
    } catch (err) {
      console.error('更新设备失败:', err);
      throw new Error(err.message || '更新设备失败');
    }
  },

  // 删除设备
  async deleteDevice(deviceId, token) {
    try {
      const res = await uni.request({
        url: `${BASE_URL}/api/devices/${deviceId}`,
        method: 'DELETE',
        header: {
          'Authorization': token,
          'Content-Type': 'application/json'
        },
        timeout: 15000
      });
      
      const response = Array.isArray(res) ? res[1] : res;
      if (!response || response.statusCode !== 200) {
        throw new Error(response ? `请求失败，状态码：${response.statusCode}` : '无效的响应');
      }
      
      return {
        code: response.data?.code || 1,
        msg: response.data?.msg || 'success',
        data: response.data?.data || response.data
      };
    } catch (err) {
      console.error('删除设备失败:', err);
      throw new Error(err.message || '删除设备失败');
    }
  }
};